<template>
  <div>
    <!-- Tab切换模块 -->
    <div style="width: 100%; height: 35px; line-height: 35px; background-color: #fff; border-bottom: 1px solid #ededed">
      <u-tabs :list="voucherList" @click="clicktabs" lineHeight="5rpx" lineWidth="100rpx"></u-tabs>
    </div>

    <div style="background-color: #f0f3fb; padding: 10px" v-if="voucherList.length > 0">
      <!-- 基本信息模块 -->
      <div style="background-color: #fff; border-radius: 5px; padding: 10px">
        <!-- 标题和删除按钮 -->
        <div style="display: flex">
          <image src="http://36.139.124.9:9000/community/img/addcomIcon.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
          <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">基础信息</div>
          <div style="margin-left: auto">
            <button
              v-if="isVendorActivity == 0"
              style="
                background-color: red;
                border-radius: 50%;
                color: #fff;
                font-size: 12px;
                height: 105rpx;
                width: 105rpx;
                border: none;
                display: flex;
                align-items: center;
                justify-content: center;
              "
              @click="delVoucher"
            >
              删除
            </button>
          </div>
        </div>

        <!-- 活动券名称输入框 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">活动券:</div>
          <input v-model="voucherForm.name" @blur="setList(voucherForm)" class="input_class" placeholder="请填写活动券名称" />
        </div>

        <!-- 活动券数量输入框 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">活动券数量:</div>
          <input type="number" v-model="voucherForm.number" class="input_class" placeholder="请输入活动券数量" />
        </div>

        <!-- 限购数量输入框 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">限购:</div>
          <input type="number" v-model="voucherForm.purchaseLimit" class="input_class" placeholder="请输入限购数量" />
        </div>

        <!-- 活动券图标上传 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">活动券图标:</div>
          <div style="margin-top: 15px">
            <u-upload
              :fileList="voucherForm.fileList"
              @afterRead="afterRead"
              height="200"
              width="200"
              @delete="deletePic"
              :name="voucherForm.id"
              :maxCount="10"
              :previewFullImage="true"
            >
              <div style="border: 1px #000000 dashed; border-radius: 3px; width: 200rpx; height: 200rpx; line-height: 200rpx; text-align: center">
                <image :src="imgurl + voucherForm.icon" style="width: 90px; height: 90px"></image>
              </div>
            </u-upload>
          </div>
        </div>
      </div>

      <!-- 详细信息模块 -->
      <div style="background-color: #fff; border-radius: 5px; padding: 10px; margin-top: 15px">
        <div style="display: flex; padding: 10px">
          <image src="http://36.139.124.9:9000/community/img/addcomIcon.png" style="width: 30px; height: 30px; margin-right: 15px"></image>
          <div style="font-family: 'PingFang_Bold'; height: 30px; line-height: 30px">详细信息</div>
        </div>

        <!-- 活动详情图片上传 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">活动详情图片:</div>
          <div style="margin-top: 15px">
            <u-upload
              :fileList="voucherForm.detailFileList"
              @afterRead="afterReadDetail"
              height="200"
              width="200"
              @delete="deleteDetailPic"
              :name="voucherForm.id"
              :maxCount="10"
              :previewFullImage="true"
            >
              <div style="border: 1px #000000 dashed; border-radius: 3px; width: 200rpx; height: 200rpx; line-height: 200rpx; text-align: center">
                <image :src="imgurl + voucherForm.graphicInfo" style="width: 90px; height: 90px"></image>
              </div>
            </u-upload>
          </div>
        </div>

        <!-- 价格输入框 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">价格:</div>
          <input type="digit" v-model="voucherForm.price" class="input_class" placeholder="请输入" />
        </div>

        <!-- 积分返还开关 -->
        <u-cell size="large" title="积分返还:" :value="typeValue" @click="getTypelx" isLink></u-cell>

        <!-- 返还积分输入框 -->
        <div style="display: flex; align-items: center" v-if="voucherForm.isIntegral == 1">
          <div style="width: 90px">返还积分:</div>
          <input type="digit" v-model="voucherForm.integralGive" class="input_class" placeholder="请输入" />
        </div>

        <!-- 物业积分抵扣比例 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">物业积分抵扣比例:</div>
          <input type="digit" v-model="voucherForm.integralComunityDiscount" class="input_class" placeholder="最大抵扣：如0.1，代表10%" />
        </div>

        <!-- 物业积分抵扣后价格 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">物业积分抵扣后价格:</div>
          <input type="digit" v-model="voucherForm.integralComunityDiscountPrice" disabled class="input_class" placeholder="自动计算（价格-抵扣比例*价格）" />
        </div>
        <!-- 自动核销开关 -->
        <u-cell size="large" title="自动核销:" :value="autoValue" @click="getAutoType" isLink></u-cell>
        <!-- 推广佣金 -->
        <div style="display: flex; align-items: center">
          <div style="width: 90px">推广佣金:</div>
          <input type="digit" v-model="voucherForm.promotionCommissions" class="input_class" placeholder="请输入" />
        </div>
        <!-- 关联商品 -->
        <u-cell-group>
          <div style="display: flex; align-items: center; justify-content: space-between; height: 40px" @click="showRight = true">
            <div>点击关联商品</div>
            <image src="../../static/z/jia.png" style="width: 20px; height: 20px; margin-right: 15px"></image>
          </div>
        </u-cell-group>

        <!-- 商品选择弹窗 -->
        <u-picker :show="showType" @cancel="showType = false" :columns="columns" keyName="categoryName" @confirm="getTsType"></u-picker>
        <u-popup :show="showRight" mode="right" @close="close" @open="open" :closeOnClickOverlay="false">
          <view style="width: 600rpx; height: 100%; display: flex; flex-direction: column">
            <view class="searchButton">
              <input v-model="keywords" class="input_class1" placeholder="请输入商品名称，关键字，商品ID" />
              <button
                style="
                  border-radius: 20rpx;
                  background-color: #007aff;
                  font-size: 14px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  color: #ffffff;
                  border: none;
                  margin-left: 10px;
                  height: 40px;
                "
                @click="searchProduct"
              >
                搜索
              </button>
            </view>

            <scroll-view class="scroll-view" scroll-y="true">
              <div
                v-for="(item, index) in spData"
                @click="selectSp(item)"
                :class="item.isSelecd ? 'isSelecd' : ''"
                :key="index"
                style="margin-top: 20px; background: #ffffff; margin-top: 10px; width: 95%; margin-left: 2.5%; box-shadow: 0 0 25px 0 #ecf3ff; padding: 10px; border-radius: 5px"
              >
                <div style="display: flex; position: relative">
                  <div style="position: absolute; right: 0; top: 0" v-show="item.isSelecd">
                    <u-icon name="checkbox-mark" color="red"></u-icon>
                  </div>
                  <image :src="imgurl + item.image" style="width: 60px; height: 60px; border-radius: 5px"></image>
                  <div>
                    <div style="font-weight: bold">{{ item.storeName }}</div>
                    <div style="color: red">￥{{ item.price }}</div>
                  </div>
                </div>
              </div>
            </scroll-view>

            <view class="confirm-button-container">
              <button v-if="isVendorActivity == 0" class="confirm-button" @click="confirmSelection">确认</button>
            </view>
          </view>
        </u-popup>

        <!-- 所选商品列表 -->
        <div v-if="okSpForm.length > 0" style="margin-top: 15px">
          <div
            v-for="(item, index) in okSpForm"
            :key="index"
            style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; padding: 10px; border: 1px solid #ccc; border-radius: 5px"
          >
            <div>
              <div style="font-weight: bold">{{ item.name }}</div>
              <div style="color: red">￥{{ item.price }}</div>
            </div>
            <div>
              <input v-model="item.unmber" type="number" min="0" style="width: 60px; padding: 5px; border: 1px solid #ccc; border-radius: 5px; margin-right: 10px" />
            </div>
          </div>
        </div>
      </div>
      <!-- 自动核销选择器 -->
      <u-picker :show="showAutoType" @cancel="showAutoType = false" :columns="columns" keyName="categoryName" @confirm="getAutoTsType"></u-picker>
      <!-- 日期范围选择弹窗 -->
      <u-calendar :show="show" :mode="mode" rowHeight="100" @confirm="confirm"></u-calendar>

      <!-- 保存按钮 -->
      <u-button v-if="isVendorActivity == 0" type="primary" @click="addOwner">保存</u-button>

      <!-- 新增消费券按钮 -->
    </div>
    <div style="position: fixed; bottom: 650rpx; right: 20px; z-index: 1000" v-if="addBtnShow">
      <button
        v-if="isVendorActivity == 0"
        style="
          background-color: #007aff;
          border-radius: 50%;
          color: wheat;
          font-size: 12px;
          height: 105rpx;
          width: 105rpx;
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
        "
        @click="addVoucher"
      >
        新增
      </button>
    </div>
  </div>
</template>

<script>
// Vue 组件代码
import { categorylist, addOrUpdateReId, merlist, activityById, productlist, addOrUpdateGather, delProduct, delTicket } from '../../utils/request_sh.js';
import { IMG_URL } from '../../config/index.js';
export default {
  data() {
    return {
      imgurl: IMG_URL,
      addBtnShow: true, // 是否显示新增按钮
      voucherForm: {
        number: '', // 活动券数量
        purchaseLimit: '', // 限购数量
        price: '', // 活动券名称
        integralGive: '', // 活动券图标
        integralComunityDiscount: '', // 物业积分抵扣比例
        isAuto: 0 // 自动核销开关 0关闭 1开启
      }, // 活动券表单数据
      autoValue: '关闭', // 自动核销显示值
      showAutoType: false, // 是否显示自动核销选择器
      showRight: false, // 是否显示右侧弹窗
      typeValue: '', // 积分返还类型
      showType: false, // 是否显示时间选择器
      columns: [], // 时间选择器的数据源
      xiaoqumingc: '请选择小区', // 小区选择提示
      isType: '1', // 类型标识
      title: '', // 标题
      content: '', // 内容
      complaintCategory: '', // 投诉分类
      complaintCategorys: '', // 投诉分类选项
      estateId: '', // 小区ID
      voucherList: [], // 活动券列表
      checkboxValue1: [], // 新增分页参数
      pageNum: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      hasMore: true, // 是否有更多数据
      loading: false, // 是否正在加载
      spForm: [], // 商品表单
      okSpForm: [], // 已选择的商品
      keywords: '', // 商品搜索关键词
      spData: [], // 商品数据
      id: '', // 活动ID
      isVendorActivity: ''
    };
  },

  onLoad(option) {
    console.log('🚀 ~ onLoad ~ option:', option);
    this.id = option.id;
    this.isVendorActivity = option.isVendorActivity;
    this.getDataSp().then(() => {
      this.getSpInfo(option.id);
    });
  },

  watch: {
    'voucherForm.price': 'calculateDiscountedPrice',
    'voucherForm.integralComunityDiscount': 'calculateDiscountedPrice'
  },

  methods: {
    setList(e) {
      if (!this.addBtnShow) {
        this.voucherList.pop();
        this.voucherList.push(e);
        this.clicktabs(e);
        this.$forceUpdate();
      }
    },
    // 计算抵扣后价格
    calculateDiscountedPrice() {
      if (this.voucherForm.price && this.voucherForm.integralComunityDiscount) {
        this.voucherForm.integralComunityDiscountPrice = this.voucherForm.price * (1 - this.voucherForm.integralComunityDiscount);
      } else {
        this.voucherForm.integralComunityDiscountPrice = 0;
      }
    },

    // 删除所选商品
    removeSp(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            const removedProduct = this.okSpForm[index];
            this.okSpForm.splice(index, 1);
            // 更新spData中的选择状态
            const spDataIndex = this.spData.findIndex((spItem) => spItem.id === removedProduct.ebStoreProductId);
            if (spDataIndex !== -1) {
              this.spData[spDataIndex].isSelecd = false;
              this.confirmSelection();
            }
          }
        }
      });
    },

    // 选择商品
    selectSp(item) {
      const spDataIndex = this.spData.findIndex((spItem) => spItem.id === item.id);
      if (spDataIndex !== -1) {
        const selected = !this.spData[spDataIndex].isSelecd;
        if (selected) {
          this.spData[spDataIndex].isSelecd = true;
          if (!this.spData[spDataIndex].unmber) {
            this.spData[spDataIndex].unmber = 1; // 设置默认数量为1
          }
          this.okSpForm.push({
            ebStoreProductId: item.id,
            name: item.storeName,
            unmber: this.spData[spDataIndex].unmber,
            price: item.price,
            inventory: item.stock,
            propertyPoints: 0,
            consumePoints: 0,
            pointsReturn: 0
          });
        } else {
          this.spData[spDataIndex].isSelecd = false;
          this.okSpForm = this.okSpForm.filter((spForm) => spForm.ebStoreProductId !== item.id);
        }
      }
    },

    // 获取商品列表数据
    getDataSp() {
      return new Promise((resolve) => {
        const userInfo = uni.getStorageSync('userInfo');
        const merId = userInfo ? userInfo.merId : '';
        const params = {
          ebMerId: merId,
          userRightComand: 'shanghuAdmin',
          storeType: 3,
          keywords: this.keywords
        };
        this.spData = [];
        productlist(params).then((res) => {
          if (res.code == 200) {
            res.rows.forEach((item) => {
              item.isSelecd = false;
              this.spData.push(item);
            });
            resolve();
          }
        });
      });
    },

    // 获取商品详情
    getSpInfo(id) {
      activityById(id).then((res) => {
        if (res.code === 200) {
          this.voucherList = res.data.ebMerActivityTicketList; // 回显活动券列表
          this.clicktabs(this.voucherList[0]);
          this.initSelectedProducts();
        }
      });
    },

    // 初始化已选商品
    initSelectedProducts() {
      this.okSpForm = [];
      this.spData.forEach((spItem) => {
        if (spItem.isSelecd) {
          this.okSpForm.push({
            ebStoreProductId: spItem.id,
            name: spItem.storeName,
            unmber: spItem.unmber || 1,
            price: spItem.price,
            inventory: spItem.stock,
            propertyPoints: 0,
            consumePoints: 0,
            pointsReturn: 0
          });
        }
      });
    },

    // 打开积分返还选择器
    getTypelx() {
      this.showType = true;
      this.columns = [
        [
          { categoryName: '开启', merchantCategoryId: '1' },
          { categoryName: '关闭', merchantCategoryId: '0' }
        ]
      ];
    }, // 打开自动核销选择器
    getAutoType() {
      this.showAutoType = true;
      this.columns = [
        [
          { categoryName: '开启', merchantCategoryId: '1' },
          { categoryName: '关闭', merchantCategoryId: '0' }
        ]
      ];
    },

    // tabs切换
    clicktabs(item) {
      if (!item) {
        return;
      }
      this.voucherForm = { ...item };
      this.typeValue = this.voucherForm.isIntegral === 1 ? '开启' : '关闭';
      this.autoValue = this.voucherForm.isAuto === 1 ? '开启' : '关闭';
      // 重置关联商品选择状态
      this.okSpForm = [];
      if (!this.voucherForm.ebMerActivityTicketProductList) {
        return;
      }
      this.spData.forEach((spItem) => {
        spItem.isSelecd = false;
        const productItem = this.voucherForm.ebMerActivityTicketProductList.find((product) => product.ebStoreProductId === spItem.id);
        if (productItem) {
          spItem.isSelecd = true;
          spItem.unmber = productItem.unmber || 1; // 设置默认数量为1或之前设置的数量
          this.okSpForm.push({
            ebStoreProductId: spItem.id,
            name: spItem.storeName,
            unmber: spItem.unmber,
            price: spItem.price,
            inventory: spItem.stock,
            propertyPoints: 0,
            consumePoints: 0,
            pointsReturn: 0
          });
        }
      });
    },

    // 删除图片
    deletePic(event) {
      this.voucherForm.fileList.splice(event.index, 1);
    },

    // 上传文件处理
    async afterRead(event) {
      const result = await this.uploadFilePromise(event.file.url);
      this.voucherForm.icon = result.fileName;
      this.voucherForm.fileName = result.fileName;
    },

    // 处理活动详情图片上传
    async afterReadDetail(event) {
      const result = await this.uploadFilePromise(event.file.url);
      this.voucherForm.graphicInfo = result.fileName;
      this.voucherForm.fileName2 = result.fileName;
    },

    // 删除活动详情图片
    deleteDetailPic(event) {
      this.voucherForm.detailFileList.splice(event.index, 1);
    },

    // 确认选择的积分返还类型
    getTsType({ value }) {
      this.showType = false;
      this.typeValue = value[0].categoryName;
      this.voucherForm.isIntegral = value[0].merchantCategoryId;
    },
    // 确认选择的自动核销类型
    getAutoTsType({ value }) {
      this.showAutoType = false;
      this.autoValue = value[0].categoryName;
      this.voucherForm.isAuto = value[0].merchantCategoryId;
    },
    // 保存活动信息
    addOwner() {
      this.addBtnShow = true;
      const ebMerActivity = {
        id: this.id,
        ebMerActivityTicketList: [
          {
            ...this.voucherForm,
            ebMerActivityTicketProductList: this.okSpForm // 确保包含最新的活动券数据
          }
        ]
      };
      addOrUpdateGather(ebMerActivity).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            icon: 'none',
            title: '操作成功！'
          });
          this.getDataSp().then(() => {
            this.getSpInfo(this.id);
          });
          // setTimeout(() => {
          //   uni.navigateBack({
          //     delta: 1,
          //     animationType: 'pop-out',
          //     animationDuration: 200
          //   });
          // }, 1500);
        }
      });
    },

    // 选择商品确认按钮
    confirmSelection() {
      // 清空okSpForm数组以避免重复项
      this.okSpForm = [];

      // 循环判断正确数据存储
      this.spData.forEach((item) => {
        if (item.isSelecd) {
          this.okSpForm.push({
            ebStoreProductId: item.id,
            name: item.storeName,
            unmber: item.unmber || 1, // 修复拼写错误
            price: item.price,
            inventory: item.stock,
            propertyPoints: 0,
            consumePoints: 0,
            pointsReturn: 0
          });
        }
      });
      this.showRight = false;
    },

    // 上传文件请求
    uploadFilePromise(url) {
      const userInfo = uni.getStorageSync('userInfo');
      const token = userInfo ? userInfo.token : '';
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          header: {
            Authorization: token
          },
          url: this.imgurl + '/api/adminApph7/common/upload',
          filePath: url,
          name: 'file',
          formData: {
            user: 'test'
          },
          success: (res) => {
            resolve(JSON.parse(res.data));
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    // 右侧弹窗打开处理
    open() {
      // console.log('open');
    },

    // 右侧弹窗关闭处理
    close() {
      this.showRight = false;
      // console.log('close');
    },

    // 新增消费券
    addVoucher() {
      this.addBtnShow = false;
      const newVoucher = {
        name: '',
        number: '',
        purchaseLimit: '',
        icon: '',
        graphicInfo: '',
        fileList: [],
        detailFileList: [],
        price: '',
        isIntegral: 0,
        integralGive: '',
        integralComunityDiscount: '',
        integralComunityDiscountPrice: '',
        ebMerActivityTicketProductList: [],
        isAuto: 0 // 默认关闭自动核销
      };

      this.voucherList.push(newVoucher);
      this.clicktabs(newVoucher);
    },

    // 删除活动券
    delVoucher() {
      if (!this.voucherForm.id) {
        this.clicktabs(this.voucherList[0]);
        this.initSelectedProducts();
        this.voucherList.pop();
        this.addBtnShow = true;
        return;
      }
      uni.showModal({
        title: '提示',
        content: '确定要删除吗？',
        success: (res) => {
          if (res.confirm) {
            delTicket(this.voucherForm.id).then((res) => {
              if (res.code === 200) {
                uni.showToast({
                  icon: 'none',
                  title: '删除成功！'
                });
                this.getDataSp().then(() => {
                  this.getSpInfo(this.id);
                  this.clicktabs(this.voucherList[0]);
                });
              }
            });
          }
        }
      });
    }
  }
};
</script>

<style lang="scss">
/* 样式优化 */
.textarea_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}

.isSelecd {
  border: 1px solid red;
  box-sizing: border-box;
}

.input_class {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  margin-top: 10px;
  font-size: 13px;
}

.input_class1 {
  background-color: #f0f3fb;
  border-radius: 5px;
  width: calc(100% - 100px);
  padding: 12px;
  font-size: 13px;
}

.searchButton {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}

.scroll-view {
  height: 82vh;
}

.confirm-button-container {
  padding: 10px;
  text-align: center;
  background-color: white;
  position: fixed;
  width: 600rpx;
  bottom: 0;
  z-index: 1;
}

.confirm-button {
  width: 80%;
  height: 40px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
}
</style>
